package slr.comment.portlet.data;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import slr.comment.model.SlrGraph;
import slr.comment.portlet.SlrCommentApplication;
import slr.comment.portlet.util.Lang;
import slr.comment.service.SlrGraphLocalServiceUtil;

import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.Argument;
import com.jaspersoft.jasperserver.irplugin.wsclient.FileContent;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.util.portlet.PortletProps;
import com.vaadin.ui.Label;
/**
 * This class is for displaying the Graphs.
 * @author TransIT mPower Labs
 *
 */
public class SLRGraphList {
	private static final long serialVersionUID = 1L;

	public SLRGraphList() {

	}
/**
 * It returns the Graph correponding the graph being selected.
 * @param SlrGraphId 
 * @return Label containing the Graph
 */
	public Label getList(long SlrGraphId) {
		SlrGraph graph = null;
		try {
			graph = SlrGraphLocalServiceUtil.getSlrGraph(SlrGraphId);
			if (Validator.isNull(graph)) {

				return new Label(Lang.getKey("slr.comment.no-graphs-available"));
			}
		} catch (SystemException e) {
			_log.error(e.getMessage());
		} catch (PortalException e) {
			_log.error(e.getMessage());
		}

		String username = PortletProps.get("username");
		String password = PortletProps.get("password");
		com.jaspersoft.jasperserver.sample.WSClient client = new com.jaspersoft.jasperserver.sample.WSClient(
				PortletProps.get("webservice.url"), username, password);

		final Label reportContent = new Label();
		final StringBuilder graphContent = new StringBuilder();
		String currentUri = graph.getJSReportUri();
		java.io.OutputStream os = null;
		try {

			List<Argument> arguments = new java.util.ArrayList<Argument>();
			Map<?, ?> files = null;

			arguments.add(new Argument(Argument.RUN_OUTPUT_IMAGES_URI, SlrCommentApplication.contextPath + "/tmp/"));
			arguments.add(new Argument(Argument.RUN_OUTPUT_FORMAT, Argument.RUN_OUTPUT_FORMAT_HTML));
			HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
			files = client.runReport(currentUri, hashMap, arguments);

			FileContent reportFile = (FileContent) files.get("report");
			File tmp = new File(SlrCommentApplication.filePath + "/tmp/");
			tmp.mkdir();
			File file = new File(SlrCommentApplication.filePath + "/tmp/test_report_.html");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(reportFile.getData());
			fos.close();
			reportFile = null;

			Iterator<?> keys = files.keySet().iterator();

			while (keys.hasNext()) {
				String imageName = (String) keys.next();
				if (!imageName.equals("report")) {
					File f = new File(tmp.getAbsolutePath() + "/" + imageName);
					FileOutputStream fs = new FileOutputStream(f);
					fs.write(((FileContent) files.get(imageName)).getData());

					fs.close();
				}
			}
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream mybuffer = null;
			DataInputStream datainput = null;

			mybuffer = new BufferedInputStream(fis);
			datainput = new DataInputStream(mybuffer);

			while (datainput.available() != 0) {
				@SuppressWarnings("deprecation")
				String eachLine = datainput.readLine().toString();
				graphContent.append(eachLine);
			}
			fis.close();

		} catch (Exception ex) {
			_log.error(ex.getMessage());
			if (os == null) {
				graphContent.append("<h1>Error running report</h1><code>");
				graphContent.append(ex.getMessage() + "</code>");
			}
			return new Label(Lang.getKey("slr.comment.no-graphs-available"));
		}

		reportContent.setValue(graphContent.toString());
		reportContent.setContentMode(Label.CONTENT_XHTML);
		return reportContent;

	}
    private static Log _log = LogFactoryUtil.getLog(SLRGraphList.class);

}